package com.zx.mes.log.aspectj;


import com.alibaba.fastjson.JSON;
import com.zx.mes.log.annotation.AroundLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * around 环绕日志打印
 *
 * @author hyl
 * @date 2018-5-9
 */
@Aspect
@Component
public class AroundLogAspectJ {

    /**
     * 环绕注解
     *
     * @param pjd       ProceedingJoinPoint
     * @param aroundLog AroundLog获得注解
     * @return 返回方法所返回的值
     */
    @Around("execution(* com.zx.mes..*.*(..)) && @annotation(aroundLog)")
    public Object around(ProceedingJoinPoint pjd, AroundLog aroundLog) {
        long timeMillis = System.currentTimeMillis();
        /* 指定哪个类的log **/
        Logger logger = LoggerFactory.getLogger(aroundLog.type());
        String methodName = pjd.getSignature().getName();
        logger.info("方法名:[{}],开始执行", methodName);
        Object[] argsValues = pjd.getArgs();
        String[] parameterNames = ((CodeSignature) pjd.getSignature()).getParameterNames();
        for (int i = 0; i < parameterNames.length; i++) {
            logger.info("参数名:[{}],参数值:[{}]", parameterNames[i], JSON.toJSONString(argsValues[i]));
        }
        Object result = null;
        try {
            result = pjd.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        logger.info("方法名:[{}],执行完成", methodName);
        long timeMillis2 = System.currentTimeMillis();
        logger.info("方法名:[{}],执行时间[{}]ms", methodName, timeMillis2 - timeMillis);
        return result;
    }
}
